<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/8/2
 * Time: 13:20
 */

namespace app\api\controller\deliver\v1;


use app\api\model\Capital;
use app\api\model\Contract;
use app\api\model\OrderDeliveryManagerModel;
use app\api\model\OrderPaymentNodes;
use app\api\model\PollingModel;
use app\api\model\Common;
use app\api\model\Sign;
use think\Db;
use think\Controller;
use app\api\model\Authority;
use think\Exception;
use app\api\model\Client;
use  app\api\model\OrderModel;
use app\api\model\Envelopes;

/*
 * 合同签约所有流程
 */

class CostCalculation extends Controller
{
    protected $model;
    protected $us;
    protected $newTime;
    protected $endTime;
    protected $overtime;
    
    
    public function _initialize()
    {
        $this->model = new Authority();
        
        $this->us = Authority::check(1);
        
    }
    
    public function share($order_id, $offer)
    {
        
        $do = [
            'agency' => 0,
            'data' => [
            
            ],
        ];
        if (!empty($offer['MainMaterialMoney'])) {

//            $client = new Client();
//            $client->index($order_id, 'order.contract_pdf', 'order.contract_pdf');
            $img['url'] = config('pdf_api_url') . '/api/v1/contract?order_id=' . $order_id . '&model=1';
            
            array_push($do['data'], $img);
//            contractPdf($order_id);
        }
        if (!empty($offer['agencyMoney'])) {
//            $client = new Client();
//            $client->index($order_id, 'order.agentcontract_pdf', 'order.agentcontract_pdf');
            $img['url']   = config('pdf_api_url') . '/api/v1/contract?order_id=' . $order_id . '&model=2';
            $do['agency'] = 1;
            array_push($do['data'], $img);
//            agentContractPdf($order_id);
        
        }
        
        return $do;
        
    }
    
    /*
     * 代购合同
     */
    
    
    /*
    * 合同问题
    */
    public function ContractIssues($type = 1)
    {
        
        $data = [
            [
                'title' => '墙面翻新',
                'type' => 0,
                'check' => 0,
            ],
            [
                'title' => '室内渗漏水',
                'type' => 1,
                'check' => 0,
            ],
            [
                'title' => '建筑渗漏水',
                'type' => 2,
                'check' => 0,
            ],
            [
                'title' => '局部改造',
                'type' => 3,
                'check' => 0,
            ],
            [
                'title' => '其它',
                'type' => 4,
                'check' => 0,
            ],
        ];
        if ($type == 2) {
            return $data;
        } else {
            r_date($data, 200);
        }
        
    }
    
    
    /**
     * 新板合同页面报价显示
     */
    public function ContractDisplay(Envelopes $envelopes, OrderModel $orderModel)
    {
        $data      = Authority::param(['order_id']);
        $op        = db('order')->where(['order.order_id' => $data['order_id']])
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->join('order_setting', 'order_setting.order_id=order.order_id', 'left')
            ->join('order_info', 'order.order_id=order_info.order_id', 'left')
            ->join('contract co', 'order.order_id=co.orders_id', 'left')
            ->field('order.state,order.order_agency as agency,sign.*,co.con_time as conTime,order.contacts,co.contract_id,order.addres as orderAddres,concat(order_info.city,order_info.county) as countys,order_setting.sign_type')
            ->find();
        $envelopes = $envelopes
            ->where(['envelopes.type' => 1, 'envelopes.ordesr_id' => $data['order_id']])
            ->with(['CapitalList', 'CapitalList.specsList', 'OrderList'])
            ->find();
        
        $capitalList = $envelopes['capital_list'];
        $mainPayTpe2 = [];
        foreach ($capitalList as $k => $item) {
            $mainPayTpe2[$k]['money']           = 0;
            $mainPayTpe2[$k]['proportion']      = 0;
            $mainPayTpe2[$k]['type']            = $item['capital_id'];
            $mainPayTpe2[$k]['check']           = 0;
            $mainPayTpe2[$k]['combinationName'] = '';
            if ($item['capital_id'] == $op['main_mode_type1']) {
                $mainPayTpe2[$k]['proportion']      = $op['main_pay_type1'];
                $mainPayTpe2[$k]['money']           = $op['main_pay_type1_money'] + $op['purchasing_pay_type1_money'];
                $mainPayTpe2[$k]['check']           = 0;
                $mainPayTpe2[$k]['nodeId']          = $op['auxiliary_interactive_id'];
                $mainPayTpe2[$k]['categoryName']    = $op['categoryName'];
                $mainPayTpe2[$k]['combinationName'] = $op['combination_name'];
            }
            $mainPayTpe2[$k]['title'] = $item['projectTitle'];
            
        }
        //交互标准
        $capital_id         = array_column($capitalList, 'capital_id');
        $purchasingAllMoney = [];
        $mainAllMoney       = [];
        foreach ($capitalList as $list) {
            if ($list['agency'] == 1) {
                $purchasingAllMoney[] = $list['allMoney'];
            }
            if ($list['agency'] == 0) {
                $mainAllMoney[] = $list['allMoney'];
            }
            
        }
        if ($op['confirm'] != 1 || empty($op)) {
            $envelopes['give_money']          = $envelopes['give_money'] - $envelopes['main_round_discount'];
            $envelopes['purchasing_discount'] = $envelopes['purchasing_discount'] - $envelopes['purchasing_round_discount'];
        }
        $allMoney             = array_sum($mainAllMoney) - $envelopes['give_money'] + $envelopes['expense'];
        $purchasingAllMoney   = array_sum($purchasingAllMoney) - $envelopes['purchasing_discount'] + $envelopes['purchasing_expense'];
        $auxiliaryProjectList = db('auxiliary_project_list')->whereIn('capital_id', $capital_id)->whereNull('delete_time')->field('auxiliary_id,id,capital_id')->select();
        //质保卡
        $warranty_collection             = \db('warranty_collection')->where('warranty_collection.envelopes_id', $envelopes['envelopes_id'])->where('warranty_collection.pro_types', 0)->join('warranty', 'warranty.id=warranty_collection.warranty_id', 'left')->where('warranty_collection.order_id', $envelopes['ordesr_id'])->field('warranty.title,warranty_collection.years,warranty_collection.type,warranty_collection.warranty_id,warranty_collection.id')->select();
        $orderInfo['orderId']            = $data['order_id'];
        $orderInfo['orderState']         = $op['state'];
        $orderInfo['agency']             = $op['agency'];
        $orderInfo['contractState']      = !empty($op['autograph']) ? 1 : 2;
        $orderInfo['warranty']           = count($warranty_collection);
        $orderInfo['standard']           = !empty(count($auxiliaryProjectList)) ? 1 : 0;
        $orderInfo['sumMainMoney']       = $allMoney;
        $orderInfo['sumPurchasingMoney'] = $purchasingAllMoney;
        $orderInfo['envelopesId']        = $envelopes['envelopes_id'];
        $orderInfo['throughId']          = $envelopes['through_id'];
        $engineering                     = explode(',', $op['engineering']);
        $orderInfo['approvalState']=null;
        $approval_record=db('approval_record', config('database.zong'))->where(['relation_id'=> $orderInfo['envelopesId'], 'city_id' => config('cityId'), 'order_id' => $orderInfo['orderId'],'type' => 10])->order('id desc')->find();
        if(!empty($approval_record)){
            $orderInfo['approvalState']=$approval_record['status'];
        }
        $listArray                       = $this->ContractIssues(2);
        if (is_array($engineering)) {
            foreach ($engineering as $lis) {
                foreach ($listArray as $k => $item) {
                    if ($lis == $item['type']) {
                        $listArray[$k]['check'] = 1;
                    }
                }
            }
        }
        $change_value                     = \db('approval_record', config('database.zong'))
            ->where('relation_id',  $envelopes['envelopes_id'])
            ->where('status', 0)
            ->value('change_value');
        if(empty($change_value)){
            $change_value=0;
        }
        $UserInfo['projectContent']         = $listArray;
        $UserInfo['day']                    = $envelopes['gong']+$change_value;
        $UserInfo['startTime']              = empty(trim($op['addtime'])) ? '' : date('Y-m-d', $op['addtime']);
        $UserInfo['endTime']                = empty(trim($op['uptime'])) ? '' : date('Y-m-d', $op['uptime']);
        $UserInfo['isCheckTime']            = empty($UserInfo['startTime']) ? 0 : 0;
        $UserInfo['moneyDay']               = $op['overdue_days'];
        $MainCollectionInfo['deposit']      = !empty($op['main_deposit']) ? $op['main_deposit'] : 0;
        $MainCollectionInfo['depositMoney'] = !empty($op['ding']) ? $op['ding'] : 0;
        $mainPayTpe1                        = [
            [
                'title' => "签合同当日",
                'type' => 1,
                'money' => $op['main_pay_money'] + $op['purchasing_pay__type_money'],
                'proportion' => !empty($op['main_mode_type']) ? $op['main_mode_type'] : 0,
                'check' => 0,
            ],
            [
                'title' => "开工当日",
                'type' => 2,
                'money' => $op['main_pay_money'] + $op['purchasing_pay__type_money'],
                'proportion' => !empty($op['main_mode_type']) ? $op['main_mode_type'] : 0,
                'check' => 0,
            ],
        ];
        foreach ($mainPayTpe1 as $k => $list) {
            
            if (!empty($op['main_mode_type'])) {
                if ($op['main_mode_type'] == $list['type']) {
                    $mainPayTpe1[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $mainPayTpe1[$k]['check'] = 1;
                }
                
            }
        }
        $mainPayTpe3[] = [
            'title' => "全部项目",
            'type' => 1,
            'money' => $op['main_pay_type2_money'] + $op['purchasing_pay_type2_money'],
            'proportion' => !empty($op['main_mode_type2']) ? $op['main_mode_type2'] : 0,
        ];
        foreach ($mainPayTpe3 as $k => $list) {
            if (!empty($op['main_mode_type2'])) {
                if ($op['main_mode_type2'] == $list['type']) {
                    $mainPayTpe3[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $mainPayTpe3[$k]['check'] = 1;
                }
            }
        }
        if ($op['sign_type'] == 2) {
            $MainCollectionInfo['principalContractRatioOne']   = null;
            $MainCollectionInfo['principalContractRatioTwo']   = ['one' => 0.7, 'two' => 0.3];
            $MainCollectionInfo['principalContractRatioThere'] = null;
            if ((config('cityId') == 241 || config('cityId') == 205) && ($allMoney+$purchasingAllMoney) >= 10000) {
                $MainCollectionInfo['principalContractRatioOne']   = ['one' => 1];
                $MainCollectionInfo['principalContractRatioTwo']   = ['one' => 0.9, 'two' => 0.1];
                $MainCollectionInfo['principalContractRatioThere'] = ['one' => 0.5, 'two' => 0.45, 'three' => 0.05];
                
            } elseif ((config('cityId') == 241 || config('cityId') == 205) && ($allMoney+$purchasingAllMoney) < 10000) {
                $MainCollectionInfo['principalContractRatioOne']   = ['one' => 1];
                $MainCollectionInfo['principalContractRatioTwo']   = null;
                $MainCollectionInfo['principalContractRatioThere'] = null;
            } elseif (config('cityId') == 172) {
                $MainCollectionInfo['principalContractRatioOne']   = ['one' => 1];
                $MainCollectionInfo['principalContractRatioTwo']   = null;
                $MainCollectionInfo['principalContractRatioThere'] = ['one' => 0.5, 'two' => 0.4, 'three' => 0.1];
            } elseif (config('cityId') == 200 || config('cityId') == 239 || config('cityId') == 216) {
                $MainCollectionInfo['principalContractRatioOne']   = ['one' => 1];
                $MainCollectionInfo['principalContractRatioTwo']   = ['one' => 0.7, 'two' => 0.3];
                $MainCollectionInfo['principalContractRatioThere'] = null;
            } elseif (config('cityId') == 375) {
                $MainCollectionInfo['principalContractRatioOne']   = ['one' => 1];
                $MainCollectionInfo['principalContractRatioTwo']   = ['one' => 0.8, 'two' => 0.2];
                $MainCollectionInfo['principalContractRatioThere'] = null;
            }
            if ($orderInfo['sumMainMoney'] == 0 && $orderInfo['sumPurchasingMoney'] != 0) {
                $MainCollectionInfo['principalContractRatioOne']   = ['one' => 1];
                $MainCollectionInfo['principalContractRatioTwo']   = ['one' => 0.9, 'two' => 0.1];
                $MainCollectionInfo['principalContractRatioThere'] = null;
            }
        } else {
            $MainCollectionInfo['principalContractRatioTwo']   = ['one' => 0.9, 'two' => 0.1];
            $MainCollectionInfo['principalContractRatioThere'] = ['one' => 0.5, 'two' => 0.45, 'three' => 0.05];
            $MainCollectionInfo['purchasingProportionTwo']     = ['one' => 0.9, 'two' => 0.1];
        }
        
        
        $MainCollectionInfo['mainPayTpe1']     = $mainPayTpe1;
        $MainCollectionInfo['mainPayTpe2']     = $mainPayTpe2;
        $MainCollectionInfo['mainPayTpe3']     = $mainPayTpe3;
        $MainCollectionInfo['pay']             = !empty($op['main_pay_once']) ? $op['main_pay_once'] : 1;
        $MainCollectionInfo['additionalTerms'] = !empty($op['additional']) ? $op['additional'] : '';
//        $MainCollectionInfo['childProportion']      = [0.4, 0.3, 0.2];
//        $MainCollectionInfo['projectOneProportion'] = [0.5, 0.6, 0.7, 0.8];
        
        
        $purchasingPayTpe1      = [
            [
                'title' => "签合同当日",
                'type' => 1,
                'money' => !empty($op['purchasing_pay__type_money']) ? $op['purchasing_pay__type_money'] : 0,
                'proportion' => !empty($op['purchasing_pay_type']) ? $op['purchasing_pay_type'] : 0,
                'check' => 0,
            ],
            [
                'title' => "开工当日",
                'type' => 2,
                'money' => !empty($op['purchasing_pay__type_money']) ? $op['purchasing_pay__type_money'] : 0,
                'proportion' => !empty($op['purchasing_pay_type']) ? $op['purchasing_pay_type'] : 0,
                'check' => 0,
            ],
        ];
        $purchasingTpe2      [] = [
            'title' => "全部项目",
            'type' => 1,
            'check' => 1,
            'money' => !empty($op['purchasing_pay_type1_money']) ? $op['purchasing_pay_type1_money'] : 0,
            'proportion' => !empty($op['purchasing_pay_type1']) ? $op['purchasing_pay_type1'] : 0,
        ];
        foreach ($purchasingPayTpe1 as $k => $list) {
            if (!empty($op['purchasing_mode_type'])) {
                if ($op['purchasing_mode_type'] == $list['type']) {
                    $purchasingPayTpe1[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $purchasingPayTpe1[$k]['check'] = 1;
                }
                
            }
            
        }
        foreach ($purchasingTpe2 as $k => $list) {
            if (!empty($op['purchasing_mode_type1'])) {
                if ($op['purchasing_mode_type1'] == $list['type']) {
                    $purchasingTpe2[$k]['check'] = 1;
                }
            } else {
                if ($k == 0) {
                    $purchasingTpe2[$k]['check'] = 1;
                }
                
            }
            
        }
        
        $PurchasingInfo['pay']                   = !empty($op['purchasing_pay_once']) ? $op['purchasing_pay_once'] : 1;
        $PurchasingInfo['additionalTerms']       = !empty($op['additional_agent']) ? $op['additional_agent'] : '';
        $PurchasingInfo['purchasingPayTpe1']     = $purchasingPayTpe1;
        $PurchasingInfo['purchasingTpe2']        = $purchasingTpe2;
        $CollectionInformation['PurchasingInfo'] = $PurchasingInfo;
        if(empty($op['addres']) ){
          $address=$op['countys'].$op['orderAddres'];
            if(preg_match("/".$op['countys']."/",$op['orderAddres'])){
                $address=$op['orderAddres'];
            }
        }else{
            $address= $op['addres'] ;
        }
        $contractInfo['username']     ='';
        $contractInfo['idnumber']     = $op['idnumber'];
        $contractInfo['address']      = '';
        $contractInfo['contractpath'] = $op['contractpath'];
        $contractInfo['agency_img']   = $op['agency_img'];
        $contractInfo['overdueDays']  = $op['overdue_days'];
        $contractInfo['conTime']      = empty($op['conTime']) ? '' : date('Y-m-d H:i', $op['conTime']);
        if (!empty($op['sign_id'])) {
            
            if (empty($op['autograph']) && empty($op['contractpath']) && empty($op['agency_img'])) {
                
                $do = $this->share($data['order_id'], ['mainContract' => $allMoney, 'agency' => $purchasingAllMoney]);
            } else {
                $do = [
                    'agency' => 0,
                    'data' => [],
                ];
                if (!empty($op['contractpath'])) {
                    $img['url'] = $op['contractpath'];
                    array_push($do['data'], $img);
                }
                if (!empty($op['agency_img'])) {
                    $img['url']   = $op['agency_img'];
                    $do['agency'] = 1;
                    array_push($do['data'], $img);
                }
                $contract_id = db('contract')->where(['orders_id' => $data['order_id']])->find();
                if (empty($contract_id)) {
                    $id = db('contract')->insertGetId(['orders_id' => $data['order_id'], 'contracType' => 2, 'con_time' => $op['con_time'], 'capital_main_total' => is_array($mainAllMoney)?array_sum($mainAllMoney):0, 'capital_agent_total' =>is_array($purchasingAllMoney)? array_sum($purchasingAllMoney):0, 'main_give_money' => $envelopes['give_money'], 'agent_give_money' => $envelopes['purchasing_discount'], 'main_expense' => $envelopes['expense'], 'agent_expense' => $envelopes['purchasing_expense'], 'created_at' => time()]);
                    $orderModel->where(['order_id' => $data['order_id']])->update(['contract_id' => $id]);
                }
                $contractInfo['conTime'] = date('Y-m-d H:i', $op['con_time']);
            }
            if (empty($do['data'])) {
                $do = null;
            }
            $UserInfo['data'] = $do;
        } else {
            $UserInfo['data'] = null;
        }
        $MainCollectionInfo['payTypeMoney']=10000;
        $CollectionInformation['MainCollectionInfo'] = $MainCollectionInfo;
        $op                                          = ['userInfo' => $contractInfo, 'orderInfo' => $orderInfo, 'contractInfo' => $UserInfo, 'collectionInformation' => $CollectionInformation];
        
        r_date($op, 200);
    }
    
    public function ContractAllocation()
    {
        $pamer = Authority::param(['type', 'id']);
        if ($pamer['id'] == 1) {
            switch ($pamer['type']) {
                case 1:
                    $data = ['one' => 1];
                    break;
                case 2:
                    $data = ['one' => 0.9, 'two' => 0.1];
                    break;
                default:
                    $data = ['one' => 0.5, 'two' => 0.45, 'three' => 0.05];
            }
        } else {
            switch ($pamer['type']) {
                case 1:
                    $data = ['one' => 1];
                    break;
                case 2:
                    $data = ['one' => 0.9, 'two' => 0.1];
                    break;
                
            }
        }
        
        r_date($data, 200);
    }
    
    /*
     * 贝壳收款比例
     */
    public function shellPaymentRatio()
    {
    
    
    }
    
    /*
     *收款比例
     */
    public function collectionRatio()
    {
        $pamer = Authority::param(['type', 'id']);
        if ($pamer['id'] == 1) {
            switch ($pamer['type']) {
                case 1:
                    $data = [1];
                    break;
                case 2:
                    $data = [0.9];
                    break;
                default:
                    $data = [0.5];
            }
        } else {
            switch ($pamer['type']) {
                case 1:
                    $data = [1];
                    break;
                case 2:
                    $data = [0.9];
                    break;
                
            }
        }
        
        r_date($data, 200);
    }
    
    /**
     * 电子合同
     */
    public function sign(OrderModel $orderModel, Envelopes $envelopes, Sign $sign)
    {
        $data             = Authority::param(['data', 'projectInfo']);
        $listArray        = json_decode($data['data'], true);
        $projectInfoArray = json_decode($data['projectInfo'], true);
        $op               = db('order')
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->join('envelopes', 'envelopes.ordesr_id=order.order_id and envelopes.type=1', 'left')
            ->field('order.assignor,order.order_no,sign.*,envelopes.purchasing_discount,envelopes.envelopes_id,envelopes.main_round_discount,envelopes.purchasing_round_discount,envelopes.give_money')
            ->where(['order.order_id' => $listArray['orderInfo']['orderId']])
            ->find();
        $approval_record=\db('approval_record', config('database.zong'))->where(['order_id' => $listArray['orderInfo']['orderId'], 'relation_id' => $op['envelopes_id'],'status' => 0, 'type' => 10])->find();
        if (!empty($approval_record)) {
            r_date(null, 300, '报价时申请了超出最大范围的工期时间，需待城市总审核通过后才可使用该时间签约。');
        }
        if ($op['confirm'] == 1) {
            r_date(null, 300, '该订单用户已签字');
        }
        if(empty($listArray['userInfo']['address'])){
            r_date(null, 300, '请输入地址');
        }
        if(empty($listArray['userInfo']['username'])){
            r_date(null, 300, '请输入姓名');
        }
        $envelopes->where('ordesr_id', $listArray['orderInfo']['orderId'])->where('type', 1)->Update(['main_round_discount' => 0, 'give_money' => ['dec', $op['main_round_discount']], 'purchasing_discount' => ['dec', $op['purchasing_round_discount']], 'purchasing_round_discount' => 0]);
        $offer = $orderModel->TotalProfit($listArray['orderInfo']['orderId']);
        $o = $sign->signAdd($orderModel, $listArray, $projectInfoArray, $op, $offer, $this->us['user_id']);
        $envelopes->where('ordesr_id', $listArray['orderInfo']['orderId'])->where('type', 1)->Update(['gong' => $listArray['contractInfo']['day'], 'main_round_discount' => $o['main_round_discount'], 'give_money' => ['inc', $o['main_round_discount']], 'purchasing_discount' => ['inc', $o['purchasing_round_discount']], 'purchasing_round_discount' => $o['purchasing_round_discount']]);
        $do = $this->share($listArray['orderInfo']['orderId'], $offer);
        r_date($do, 200);
        
    }
    
    /*
     * 合同重签
     */
    public function Countersign()
    {
        $data    = Authority::param(['orderId']);
        $payment = db('payment')->where('orders_id', $data['orderId'])->find();
        if (!empty($payment)) {
            r_date(null, 300, '订单已发起付款，不能重签');
        }
        db('contract')->where('orders_id', $data['orderId'])->delete();
        db('capital_schedule')->where('order_id', $data['orderId'])->delete();
        db('order_times')->where('order_id', $data['orderId'])->update(['signing_time' => 0]);
        db('sign')->where('order_id', $data['orderId'])->update(['autograph' => '', 'contractpath' => '', 'agency_img' => '', 'confirm' => 3]);
        $envelopes        = db('envelopes')->where('type', 1)->where('ordesr_id', $data['orderId'])->find();
        $envelopes_coupon = db('envelopes_coupon')->where('envelopes_id', $envelopes['envelopes_id'])->select();
        if (!empty($envelopes['main_id'])) {
            db('coupon_user', config('database.zong'))->where('id', $envelopes['main_id'])->update(['usage_status' => 1, 'usage_time' => 0, 'usage_type' => 0, 'usage_user_type' => 0, 'usage_user' => 0]);
        }
        if (!empty($envelopes['purchasing_id'])) {
            db('coupon_user', config('database.zong'))->where('id', $envelopes['purchasing_id'])->update(['usage_status' => 1, 'usage_time' => 0, 'usage_type' => 0, 'usage_user_type' => 0, 'usage_user' => 0]);
        }
        if (!empty($envelopes_coupon)) {
            foreach ($envelopes_coupon as $i) {
                if (!empty($i['main_id'])) {
                    db('coupon_user', config('database.zong'))->where('id', $i['main_id'])->update(['usage_status' => 1, 'usage_time' => 0, 'usage_type' => 0, 'usage_user_type' => 0, 'usage_user' => 0]);
                }
                if (!empty($i['purchasing_id'])) {
                    db('coupon_user', config('database.zong'))->where('id', $i['purchasing_id'])->update(['usage_status' => 1, 'usage_time' => 0, 'usage_type' => 0, 'usage_user_type' => 0, 'usage_user' => 0]);
                }
                
            }
            
        }
        Db::connect(config('database.zong'))->table('order_payment_nodes')->where('order_id', $data['orderId'])->delete();
        
        r_date(null, 200);
    }
    
    /**
     * 新板合同分享页面
     */
    public function ContractSharing(Envelopes $envelopes)
    {
        
        $data = Authority::param(['orderId']);
        $op   = db('order')->where(['order.order_id' => $data['orderId']])
            ->join('chanel', 'order.channel_id=chanel.id', 'left')
            ->join('contract', 'order.order_id=contract.orders_id', 'left')
            ->join('goods_category', 'order.pro_id=goods_category.id', 'left')
            ->field('order.contacts,insert(order.telephone,4,4,"****") as telephone,order.addres,FROM_UNIXTIME(contract.con_time,"%Y-%m-%d ")as chanel,goods_category.title')
            ->find();
        
        $length = 4;
        preg_match_all("/./us", $op['addres'], $match);
        $len = count($match[0]);
        if ($len > 4) {
            $address = mb_substr($op['addres'], 0, $len - $length) . '****';
        } else {
            $address = mb_substr($op['addres'], 0, $len - 1) . '****';
        }
        $op['addres']       = $address;
        $envelopes          = $envelopes
            ->where(['envelopes.type' => 1, 'envelopes.ordesr_id' => $data['orderId']])
            ->with(['CapitalList', 'CapitalList.specsList'])
            ->find();
        $result             = array();
        $tageList           = [];
        $purchasingAllMoney = [];
        $mainAllMoney       = [];
        foreach ($envelopes['capital_list'] as $k => $v) {
            $v['specsList'] = $v['specs_list'];
            unset($v['specs_list']);
            
            if ($v['agency'] == 1) {
                $purchasingAllMoney[] = $v['allMoney'];
            }
            if ($v['agency'] == 0) {
                $mainAllMoney[] = $v['allMoney'];
            }
            $result[$v['categoryName']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            $schemeTag['data']  = $result[$k];
            $tageList[]         = $schemeTag;
        }
        
        $envelopesList['expense']             = sprintf('%.2f', $envelopes['expense']);
        $envelopesList['give_money']          = sprintf('%.2f', $envelopes['give_money']);
        $envelopesList['purchasing_discount'] = sprintf('%.2f', $envelopes['purchasing_discount']);
        $envelopesList['purchasing_expense']  = sprintf('%.2f', $envelopes['purchasing_expense']);
        $envelopesList['allMoney']            = sprintf('%.2f', array_sum($mainAllMoney));
        $envelopesList['purchasingAllMoney']  = sprintf('%.2f', array_sum($purchasingAllMoney));
        $userInfo['username']                 = $this->us['username'];
        $userInfo['storeName']                = $this->us['store_name'];
        $op                                   = ['userInfo' => $userInfo, 'orderInfo' => $op, 'contractAmount' => $envelopesList, 'detailedList' => []];
        r_date($op, 200);
    }
    
    /*
     * 三级联动
     */
    public function ContractLevel()
    {
        
        $data          = Authority::param(['orderId']);
        $envelopesList = db('capital')
            ->where(['ordesr_id' => $data['orderId'], 'types' => 1, 'enable' => 1, 'agency' => 0, 'give' => 0])
            ->field('capital_id,categoryName,projectId,class_b')
            ->select();
        $sign          = db('sign')->where('order_id', $data['orderId'])->find();
        foreach ($envelopesList as $k => $item) {
            if ($item['capital_id'] == $sign['main_mode_type1']) {
                $envelopesList[$k]['select'] = 1;
            } else {
                $envelopesList[$k]['select'] = 0;
            }
            
            $envelopesList[$k]['data'] = db('auxiliary_relation')
                ->join('auxiliary_interactive', 'auxiliary_interactive.parents_id=auxiliary_relation.auxiliary_interactive_id')
                ->field('auxiliary_interactive.id,auxiliary_interactive.title')->where('pro_types', 0)->where('serial_id', $item['projectId'])->select();
        }
        $result   = array();
        $tageList = [];
        foreach ($envelopesList as $k => $v) {
            if (!empty($v['data'])) {
                foreach ($v['data'] as $o => $datum) {
                    if ($datum['id'] == $sign['auxiliary_interactive_id']) {
                        $v['data'][$o]['select'] = 1;
                    } else {
                        $v['data'][$o]['select'] = 0;
                    }
                    
                }
            }
            $result[$v['categoryName']][] = $v;
            unset($envelopesList[$k]['categoryName']);
        }
        foreach ($result as $k => $list) {
            $schemeTag['title'] = $k;
            
            if ($k == $sign['categoryName']) {
                $schemeTag['select'] = 1;
            } else {
                $schemeTag['select'] = 0;
            }
            $schemeTag['data'] = $result[$k];
            $tageList[]        = $schemeTag;
        }
        r_date($tageList, 200);
    }
    
    public function NewRule(OrderDeliveryManagerModel $deliveryManagerModel)
    {
        $data         = Authority::param(['orderId']);
        $IsStartupDelivere=$deliveryManagerModel->IsStartupDeliverer($data['orderId'],$this->us['user_id'],'');
        if(!empty($IsStartupDelivere)){
            r_date(null, 300, '请接单后再操作');
        }
        $payment_type = db('order_setting')->where('order_id', $data['orderId'])->value('payment_type');
        $new_payment  = 0;
        //等于1老的收款方式2新的
        if ($payment_type == 1) {
            $new_payment = 2;
        } elseif ($payment_type == 2) {
            $new_payment = 1;
        } elseif ($payment_type == 3) {
            $new_payment = 2;
        }
        r_date($new_payment, 200);
        
    }
    
    /*
     * 纸质合同签约
     */
    public function photoSigning(OrderModel $orderModel, Sign $sign, OrderPaymentNodes $paymentNodes, Contract $contract, Envelopes $envelopes, Capital $capital,Common $common)
    {
        $data             = Authority::param(['data', 'projectInfo', 'paperImg', 'collection']);
        $listArray        = json_decode($data['data'], true);
        $projectInfoArray = json_decode($data['projectInfo'], true);
        $paperImg         = json_decode($data['paperImg'], true);
        $collection       = json_decode($data['collection'], true);
        $op               = db('order')
            ->join('sign', 'order.order_id=sign.order_id', 'left')
            ->field('order.assignor,order.order_no,sign.*,order.company_id,order.state')
            ->where(['order.order_id' => $listArray['orderInfo']['orderId']])
            ->find();
        $envelopesInfo     = $envelopes->where('ordesr_id', $listArray['orderInfo']['orderId'])->where('type', 1)->find();
        $approval_record=\db('approval_record', config('database.zong'))->where(['order_id' => $listArray['orderInfo']['orderId'], 'relation_id' => $envelopesInfo['envelopes_id'],'status' => 0, 'type' => 10])->find();
        if (!empty($approval_record)) {
            r_date(null, 300, '报价时申请了超出最大范围的工期时间，需待城市总审核通过后才可使用该时间签约。');
        }
        $offer            = $orderModel->TotalProfit($listArray['orderInfo']['orderId']);
        $sign->startTrans();
        $capital->startTrans();
        $paymentNodes->startTrans();
        $contract->startTrans();
        $envelopes->startTrans();
        try {
            $paymentNodes->where(['order_id' => $listArray['orderInfo']['orderId']])->delete();
            $order_setting = db('order_setting')->where(['order_id' => $listArray['orderInfo']['orderId']])->find();
            if ($order_setting['payment_type'] == 3) {
                $partnership_config = db('partnership_config', config('database.zong'))->where(['id' => $order_setting['partnership_config_id']])->value('payment_config_id');
            }
            if (empty($partnership_config)) {
                r_date(null, 300, '请配置支付方式');
            }
            $singFind          = $sign->signAdd($orderModel, $listArray, $projectInfoArray, $op, $offer, $this->us['user_id'], 2);
            $offer['order_id'] = $listArray['orderInfo']['orderId'];
            $offer             = array_merge($offer, $singFind);
            $all_amount_main   = strval($offer['MainMaterialMoney']);
            $all_amount_agency = strval($offer['agencyMoney']);
            $paymentNodesFirst = $paymentNodes->generateOrderPaymentNodes($offer);
            $created_time      = time();
            $paid=[];
            $node_code=0;
            if (!empty($collection)) {
                foreach ($collection as $k => $item) {
                    if (!empty($item['voucherImg'])) {
                        $logos     = empty($item['voucherImg']) ? '' : serialize($item['voucherImg']);
                        $common->MultimediaResources($listArray['orderInfo']['orderId'],$this->us['user_id'],  empty($item['voucherImg']) ? '' : $item['voucherImg'],7);
                        $money     = bcadd($paymentNodesFirst[$k]->node_money_main, $paymentNodesFirst[$k]->node_money_agency, 2);
                        $paymentId = \db('payment')->insertGetId(['uptime' => $created_time, 'orders_id' => $listArray['orderInfo']['orderId'], 'money' => $money, 'weixin' => $partnership_config, 'success' => 1, 'material' => $paymentNodesFirst[$k]->node_money_main, 'logos' => $logos, 'agency_material' => $paymentNodesFirst[$k]->node_money_agency, 'created_time' => $created_time]);
                        $paymentNodes->isUpdate(true)->save(['payment_id' => $paymentId, 'trigger_time' => $created_time, 'id' => $paymentNodesFirst[$k]->id]);
                        if (empty($op['company_id'])) {
                            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $this->us['store_id']])->where('status', 1)->value('company_id');
                            $orderModel->where(['order_id' => $listArray['orderInfo']['orderId']])->update(['company_id' => $company_id]);
                        }
                        if($paymentNodesFirst[$k]->node_code ==0 && count(array_filter(array_column($collection,'voucherImg')))==1){
                            $node_code=1;
                        }
                        $paid[]=$paymentNodesFirst[$k]->id;
                    }
                }
                
            }
            if (!empty($paid)) {
                $paymentMoney      = db('payment')->where('payment.orders_id', $offer['order_id'])->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')->sum('money');
                \db('order_times')->where('order_id',$offer['order_id'])->where('first_payment_time',0)->update(['first_payment_time' =>$created_time]);
                if ($paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.499 && $op['state'] == 3) {
                    if (bcadd($all_amount_main, $all_amount_agency, 2) >= 10000 || (bcadd($all_amount_main, $all_amount_agency, 2) < 10000 && $node_code != 1)  || $paymentMoney >= bcadd($all_amount_main, $all_amount_agency, 2)) {
                        $orderModel->where(['order_id' => $listArray['orderInfo']['orderId']])->update(['state' => 4]);
                        remind($listArray['orderInfo']['orderId'], 4);
                        $Client = new \app\api\model\KafkaProducer();
                        $Client->add($offer['order_id'], 'u8c_bdjobbasfil_save');
                    }
                    
                }
              $ids=[];
                foreach ($paymentNodesFirst as $o){
                    if(!in_array($o->id,$paid)){
                        $ids[]=$o->id;
                    }
                }
                if(!empty($ids)){
                    $paymentNodes->isUpdate(true)->save(['node_status' => 2, 'trigger_time' => $created_time, 'id' => $ids[0]]);
                }
                
            }
            \db('order_times')->where(['order_id' => $listArray['orderInfo']['orderId']])->update(['signing_time' => $created_time]);
            $contractFind = $contract->queryOne($listArray['orderInfo']['orderId']);
            $paperImgList = empty($paperImg) ? '' : serialize($paperImg);
            if (empty($contractFind)) {
                $contractId = $contract->addQueryOne(['orders_id' => $listArray['orderInfo']['orderId'], 'contracType' => 1, 'con_time' => $created_time, 'contract' => $paperImgList, 'capital_main_total' => $offer['capital_main_total'], 'capital_agent_total' => $offer['capital_agent_total'], 'main_give_money' => $offer['main_give_money'], 'agent_give_money' => $offer['agent_give_money'], 'main_expense' => $offer['main_expense'], 'agent_expense' => $offer['agent_expense'], 'created_at' => time()]);
                $orderModel->where(['order_id' => $listArray['orderInfo']['orderId']])->update(['contract_id' => $contractId]);
            } else {
                $contract->isUpdate(true)->save(['orders_id' => $listArray['orderInfo']['orderId'], 'con_time' => $created_time, 'contract' => $paperImgList, 'contract_id' => $contractFind['contract_id'], 'capital_main_total' => $offer['capital_main_total'], 'capital_agent_total' => $offer['capital_agent_total'], 'main_give_money' => $offer['main_give_money'], 'agent_give_money' => $offer['agent_give_money'], 'main_expense' => $offer['main_expense'], 'agent_expense' => $offer['agent_expense']]);
            }
            $envelopes->where('ordesr_id', $listArray['orderInfo']['orderId'])->where('type', 1)->Update(['gong' => $listArray['contractInfo']['day']]);
            $order_setting     = db('order_setting')->where('order_id', $listArray['orderInfo']['orderId'])->find();
            db('order_aggregate')->where(['order_id'=>$listArray['orderInfo']['orderId']])->update(['sign_main_price'=>$all_amount_main,'sign_agent_price'=>$all_amount_agency]);
            $ids               = $capital->where(['types' => 1, 'enable' => 1])->where('ordesr_id', $listArray['orderInfo']['orderId'])->column('capital_id');
            $assemblyAdditions = $capital->assemblyAdditions($ids, $envelopesInfo['give_money'] - $envelopesInfo['products_main_discount_money'], $envelopesInfo['purchasing_discount'] - $envelopesInfo['products_purchasing_discount_money'], $order_setting, $envelopesInfo['expense'], $envelopesInfo['purchasing_expense']);
            $sign->commit();
            $paymentNodes->commit();
            $envelopes->commit();
            $capital->commit();
            $contract->commit();
            sendOrder($listArray['orderInfo']['orderId']);
            r_date(null, 200, '新增成功');
        } catch (Exception $e) {
            $sign->rollback();
            $capital->rollback();
            $contract->rollback();
            $envelopes->rollback();
            $paymentNodes->rollback();
            r_date(null, 300, $e->getMessage());
        }
        
        
    }
    
    /*
     * 上传凭证
     */
    public function paymentVoucher(OrderPaymentNodes $paymentNodes, OrderModel $orderModel,Common $common)
    {
        $data         = Authority::param(['orderId', 'nodeId', 'paperImgs']);
        $collection   = json_decode($data['paperImgs'], true);
        $created_time = time();
        if (!empty($collection)) {
            $logos      = empty($collection) ? '' : serialize($collection);
            $common->MultimediaResources($data['orderId'],$this->us['user_id'], empty($collection) ? [] : $collection,7);
            $order      = $orderModel->where(['order_id' => $data['orderId']])->find();
            $company_id = db('company_config', config('database.zong'))->where('find_in_set(:id,store_list)', ['id' => $this->us['store_id']])->where('status', 1)->value('company_id');
            if (empty($order['company_id'])) {
                $orderModel->where(['order_id' => $data['orderId']])->update(['company_id' => $company_id]);
            }
            $paymentNodesList  = $paymentNodes->where(['order_id' => $data['orderId']])->select();
            $node_money_main   = 0;
            $node_money_agency = 0;
            $node_code         = 0;
            $id                = [];
            foreach ($paymentNodesList as $item) {
                if ($item['id'] == $data['nodeId']) {
                    if ($item['node_code'] == 0) {
                        $node_code = 1;
                    }
                    $node_money_main   += $item['node_money_main'];
                    $node_money_agency += $item['node_money_agency'];
                }
                if ($item['node_status'] == 1 && $item['id'] != $data['nodeId']) {
                    $id[] = $item['id'];
                }
                
            }
            asort($id);
            $order_setting = db('order_setting')->where(['order_id' => $data['orderId']])->find();
            if ($order_setting['payment_type'] == 3) {
                $partnership_config = db('partnership_config', config('database.zong'))->where(['id' => $order_setting['partnership_config_id']])->value('payment_config_id');
            }
            if (empty($partnership_config)) {
                r_date(null, 300, '请配置支付方式');
            }
            $paymentId = \db('payment')->insertGetId(['uptime' => $created_time, 'orders_id' => $data['orderId'], 'money' => bcadd($node_money_main, $node_money_agency, 2), 'weixin' => $partnership_config, 'success' => 1, 'material' => $node_money_main, 'logos' => $logos, 'agency_material' => $node_money_agency, 'created_time' => $created_time]);
            $paymentNodes->isUpdate(true)->save(['payment_id' => $paymentId, 'trigger_time' => $created_time, 'id' => $data['nodeId']]);
            if (!empty($id)) {
                $paymentNodes->isUpdate(true)->save(['node_status' => 2, 'trigger_time' => $created_time, 'id' => $id[0]]);
            }
            $offer             = $orderModel->TotalProfit($data['orderId']);
            \db('order_times')->where('order_id',$data['orderId'])->where('first_payment_time',0)->update(['first_payment_time' =>$created_time]);
            $paymentMoney      = db('payment')->where('payment.orders_id', $data['orderId'])->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')->sum('money');
            $all_amount_main   = strval($offer['MainMaterialMoney']);
            $all_amount_agency = strval($offer['agencyMoney']);
            $state             = $orderModel->where(['order_id' => $data['orderId']])->value('state');
            if ($paymentMoney / bcadd($all_amount_main, $all_amount_agency, 2) >= 0.499 && $state == 3) {
                if (bcadd($all_amount_main, $all_amount_agency, 2) >= 10000 || (bcadd($all_amount_main, $all_amount_agency, 2) < 10000 && $node_code != 1)) {
                    $orderModel->where(['order_id' => $data['orderId']])->update(['state' => 4]);
                    remind($data['orderId'], 4);
                    $Client = new \app\api\model\KafkaProducer();
                    $Client->add($data['orderId'], 'u8c_bdjobbasfil_save');
                }
            }
        } else {
            r_date(null, 300, '请上传图片');
        }
        sendOrder($data['orderId']);
        r_date(null, 200, '新增成功');
    }
       
    /**
     * 合同数据
     */
    public function contractImg(){
         $data         = Authority::param(['orderId']);
        //  $contract=db('contract')->where(['order_id' => $data['orderId']])->find();
         $contract=db('sign')->where(['order_id' => $data['orderId']])->find();
         r_date(['man'=>$contract['contract_pdf_path'],'agent'=>$contract['agent_contract_pdf_path']], 200, '新增成功');
    }
    
}